package com.spring.demo.utils;


import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class TestDemo  implements ApplicationContextAware {


    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        TestDemo.applicationContext = applicationContext; // NOSONAR
    }



    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }


    /**
     * 静态调用非静态的方法
     */
    public static void demo () {

        FeijintaiTest feijintaiTest = applicationContext.getBean("feijintai", FeijintaiTest.class);

        feijintaiTest.test();

    }


}
